from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QPushButton,
                               QTableWidget, QTableWidgetItem, QDialog, QLabel,
                               QLineEdit, QComboBox, QDateEdit, QMessageBox)
from PySide6.QtCore import Qt, QDate
from models.member import Member


class MemberDialog(QDialog):
    def __init__(self, parent=None, member_data=None):
        super().__init__(parent)
        self.member_data = member_data
        self.setup_ui()
        if member_data:
            self.load_member_data()

    def setup_ui(self):
        self.setWindowTitle("会员信息")
        self.setMinimumWidth(400)

        layout = QVBoxLayout(self)

        # 创建表单字段
        form_layout = QVBoxLayout()

        # 姓名
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText("请输入姓名")
        form_layout.addWidget(QLabel("姓名:"))
        form_layout.addWidget(self.name_input)

        # 手机号
        self.phone_input = QLineEdit()
        self.phone_input.setPlaceholderText("请输入手机号")
        form_layout.addWidget(QLabel("手机号:"))
        form_layout.addWidget(self.phone_input)

        # 性别
        self.gender_combo = QComboBox()
        self.gender_combo.addItems(["男", "女"])
        form_layout.addWidget(QLabel("性别:"))
        form_layout.addWidget(self.gender_combo)

        # 出生日期
        self.birth_date = QDateEdit()
        self.birth_date.setCalendarPopup(True)
        self.birth_date.setDate(QDate.currentDate())
        form_layout.addWidget(QLabel("出生日期:"))
        form_layout.addWidget(self.birth_date)

        # 会员等级
        self.level_combo = QComboBox()
        self.level_combo.addItems(["普通会员", "白银会员", "黄金会员", "钻石会员"])
        form_layout.addWidget(QLabel("会员等级:"))
        form_layout.addWidget(self.level_combo)

        layout.addLayout(form_layout)

        # 按钮
        button_layout = QHBoxLayout()
        self.save_btn = QPushButton("保存")
        self.cancel_btn = QPushButton("取消")

        self.save_btn.clicked.connect(self.save_member)
        self.cancel_btn.clicked.connect(self.reject)

        button_layout.addWidget(self.save_btn)
        button_layout.addWidget(self.cancel_btn)

        layout.addLayout(button_layout)

    def load_member_data(self):
        """加载会员数据到表单"""
        self.name_input.setText(self.member_data["name"])
        self.phone_input.setText(self.member_data["phone"])
        self.gender_combo.setCurrentText(self.member_data["gender"])
        if self.member_data["birth_date"]:
            self.birth_date.setDate(QDate.fromString(self.member_data["birth_date"], "yyyy-MM-dd"))
        self.level_combo.setCurrentText(self.member_data["membership_level"])

    def save_member(self):
        """保存会员信息"""
        name = self.name_input.text().strip()
        phone = self.phone_input.text().strip()

        if not name or not phone:
            QMessageBox.warning(self, "警告", "姓名和手机号不能为空！")
            return

        member = Member()
        if self.member_data:
            member.id = self.member_data["id"]

        member.name = name
        member.phone = phone
        member.gender = self.gender_combo.currentText()
        member.birth_date = self.birth_date.date().toString("yyyy-MM-dd")
        member.membership_level = self.level_combo.currentText()

        try:
            member.save()
            self.accept()
        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存失败：{str(e)}")


class MemberPage(QWidget):
    def __init__(self):
        super().__init__()
        self.setup_ui()
        self.load_members()

    def setup_ui(self):
        layout = QVBoxLayout(self)

        # 工具栏
        toolbar = QHBoxLayout()

        # 搜索区域
        search_layout = QHBoxLayout()
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("输入姓名或手机号搜索")
        self.search_input.setMinimumWidth(200)
        self.search_input.textChanged.connect(self.search_members)

        search_layout.addWidget(QLabel("搜索："))
        search_layout.addWidget(self.search_input)

        # 按钮区域
        button_layout = QHBoxLayout()
        self.add_btn = QPushButton("添加会员")
        self.refresh_btn = QPushButton("刷新")
        self.points_btn = QPushButton("积分管理")

        self.add_btn.clicked.connect(self.add_member)
        self.refresh_btn.clicked.connect(self.load_members)
        self.points_btn.clicked.connect(self.manage_points)

        button_layout.addWidget(self.add_btn)
        button_layout.addWidget(self.points_btn)
        button_layout.addWidget(self.refresh_btn)

        # 将搜索区域和按钮区域添加到工具栏
        toolbar.addLayout(search_layout)
        toolbar.addStretch()
        toolbar.addLayout(button_layout)

        # 会员表格
        self.table = QTableWidget()
        self.table.setColumnCount(8)
        self.table.setHorizontalHeaderLabels([
            "ID", "姓名", "手机号", "性别", "会员等级",
            "积分", "消费总额", "操作"
        ])

        # 设置表格样式
        self.table.setSelectionBehavior(QTableWidget.SelectRows)
        self.table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.table.horizontalHeader().setStretchLastSection(True)

        layout.addLayout(toolbar)
        layout.addWidget(self.table)

    def load_members(self):
        """加载会员数据"""
        self.table.setRowCount(0)
        members = Member.get_all()

        for row, member in enumerate(members):
            self.table.insertRow(row)

            # 添加会员信息
            self.table.setItem(row, 0, QTableWidgetItem(str(member["id"])))
            self.table.setItem(row, 1, QTableWidgetItem(member["name"]))
            self.table.setItem(row, 2, QTableWidgetItem(member["phone"]))
            self.table.setItem(row, 3, QTableWidgetItem(member["gender"]))
            self.table.setItem(row, 4, QTableWidgetItem(member["membership_level"]))
            self.table.setItem(row, 5, QTableWidgetItem(str(member["points"])))
            self.table.setItem(row, 6, QTableWidgetItem(f"¥{member['total_consumption']:.2f}"))

            # 添加操作按钮
            btn_widget = QWidget()
            btn_layout = QHBoxLayout(btn_widget)
            edit_btn = QPushButton("编辑")
            delete_btn = QPushButton("删除")

            edit_btn.clicked.connect(lambda checked, m=dict(member): self.edit_member(m))
            delete_btn.clicked.connect(lambda checked, id=member["id"]: self.delete_member(id))

            btn_layout.addWidget(edit_btn)
            btn_layout.addWidget(delete_btn)
            btn_layout.setContentsMargins(0, 0, 0, 0)

            self.table.setCellWidget(row, 7, btn_widget)

    def add_member(self):
        """添加会员"""
        dialog = MemberDialog(self)
        if dialog.exec_() == QDialog.Accepted:
            self.load_members()

    def edit_member(self, member_data):
        """编辑会员"""
        dialog = MemberDialog(self, member_data)
        if dialog.exec_() == QDialog.Accepted:
            self.load_members()

    def delete_member(self, member_id):
        """删除会员"""
        reply = QMessageBox.question(
            self, "确认删除",
            "确定要删除这个会员吗？此操作不可恢复！",
            QMessageBox.Yes | QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            try:
                Member.delete(member_id)
                self.load_members()
            except Exception as e:
                QMessageBox.critical(self, "错误", f"删除失败：{str(e)}")

    def search_members(self):
        """搜索会员"""
        search_text = self.search_input.text().strip().lower()

        # 如果搜索框为空，显示所有会员
        if not search_text:
            self.load_members()
            return

        # 隐藏所有行
        for row in range(self.table.rowCount()):
            self.table.setRowHidden(row, True)

            # 获取姓名和手机号
            name = self.table.item(row, 1).text().lower()
            phone = self.table.item(row, 2).text().lower()

            # 如果搜索文本匹配，显示该行
            if search_text in name or search_text in phone:
                self.table.setRowHidden(row, False)

    def manage_points(self):
        """管理积分"""
        # 获取选中的行
        selected_rows = self.table.selectedItems()
        if not selected_rows:
            QMessageBox.warning(self, "警告", "请先选择一个会员！")
            return

        # 获取选中行的会员ID
        row = selected_rows[0].row()
        member_id = int(self.table.item(row, 0).text())

        # 获取会员信息
        member = Member.get_by_id(member_id)
        if member:
            dialog = PointsDialog(self, dict(member))
            dialog.exec_()


class PointsDialog(QDialog):
    def __init__(self, parent=None, member_data=None):
        super().__init__(parent)
        self.member_data = member_data
        self.setup_ui()

    def setup_ui(self):
        self.setWindowTitle("积分管理")
        self.setMinimumWidth(300)

        layout = QVBoxLayout(self)

        # 会员信息
        info_layout = QVBoxLayout()
        info_layout.addWidget(QLabel(f"会员：{self.member_data['name']}"))
        info_layout.addWidget(QLabel(f"当前积分：{self.member_data['points']}"))

        # 积分操作
        points_layout = QHBoxLayout()
        self.points_input = QLineEdit()
        self.points_input.setPlaceholderText("输入积分数量")
        self.add_points_btn = QPushButton("增加积分")
        self.deduct_points_btn = QPushButton("扣除积分")

        points_layout.addWidget(self.points_input)
        points_layout.addWidget(self.add_points_btn)
        points_layout.addWidget(self.deduct_points_btn)

        # 绑定事件
        self.add_points_btn.clicked.connect(lambda: self.update_points(True))
        self.deduct_points_btn.clicked.connect(lambda: self.update_points(False))

        # 添加到主布局
        layout.addLayout(info_layout)
        layout.addLayout(points_layout)

        # 关闭按钮
        close_btn = QPushButton("关闭")
        close_btn.clicked.connect(self.accept)
        layout.addWidget(close_btn)

    def update_points(self, is_add):
        """更新积分"""
        try:
            points = int(self.points_input.text())
            if points <= 0:
                raise ValueError("积分必须大于0")

            current_points = self.member_data["points"]

            if is_add:
                new_points = current_points + points
                message = f"确定要增加 {points} 积分吗？"
            else:
                if points > current_points:
                    raise ValueError("扣除积分不能大于当前积分")
                new_points = current_points - points
                message = f"确定要扣除 {points} 积分吗？"

            reply = QMessageBox.question(self, "确认", message)
            if reply == QMessageBox.Yes:
                # 更新数据库
                sql = "UPDATE members SET points = ? WHERE id = ?"
                db.execute(sql, (new_points, self.member_data["id"]))

                # 更新显示
                self.member_data["points"] = new_points
                QMessageBox.information(self, "成功", "积分更新成功！")
                self.parent().load_members()  # 刷新会员列表

                # 清空输入
                self.points_input.clear()

        except ValueError as e:
            QMessageBox.warning(self, "错误", str(e))
        except Exception as e:
            QMessageBox.critical(self, "错误", f"操作失败：{str(e)}")
